package com.yimiyisu.contract_cust.service.contract;

import com.yimiyisu.contract_cust.constant.IText_CSS;
import com.yimiyisu.contract_cust.event.model.ContractExportEventModel;
import com.yimiyisu.contract_cust.kit.HtmlToPdfKit;
import com.zen.annotation.Component;
import com.zen.kit.ConfigKit;
import com.zen.kit.StringKit;
import com.zen.kit.UploadKit;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class ContractExportService {

    public String export(ContractExportEventModel contractExportEventModel) {
        String fullHtml = "<html><head><style>"
                + IText_CSS.comonent
                + "</style></head><body>" + contractExportEventModel.getContext() + "</body></html>";
        String title = contractExportEventModel.getTitle();

        // 生成临时文件
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String localFileName = "temp_Contractpdf_export_" + timestamp + ".pdf";
        File tempFile = new File(System.getProperty("java.io.tmpdir"), localFileName);

        try {
            FileOutputStream fos = new FileOutputStream(tempFile);
            HtmlToPdfKit.convertHtmlToPdf(fullHtml, fos);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        // 生成CDN文件路径和名称
        String cdnDirectory = ConfigKit.appName() + "/" + StringKit.objectId() + "/";
        String cdnFileName = "合同_" + title + ".pdf";
        String cdnPath = cdnDirectory + cdnFileName;

        try (FileInputStream fileInputStream = new FileInputStream(tempFile)) {
            UploadKit.put(cdnPath, fileInputStream);
        } catch (IOException e) {
            System.out.println("文件上传失败: " + e.getMessage());
            cdnPath = "";
        } finally {
            // 清理临时文件
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
        return cdnPath;
    }
}
